# -*- coding: utf-8 -*-
from Api import *
from flask import render_template, url_for
from Config.error_mapping import *
from Api.api_services.api_template import interface_template
from Api.api_services.api_calculate import *
from Common.com_func import is_null
from Env import env_config as cfg
from Config.pro_config import pro_name_list
from Core.swagger_parse import swagger_prase
from Util.tool import md5
import random
from Celery_program import celery_task
from Celery_program.celery_result import redisResult

"""
    装 饰 器
"""


# 判断当前用户是否登录
def is_login():
    token = request.cookies.get("token")
    if token is not None:
        dm = db_model(table=cfg.USER_INFO, error_msg="判断当前用户是否登录")
        res_dict = dm.query_db(query={"token": token}, is_many=False)
        if res_dict and res_dict.get("status") == 1:
            return True
    return False


# 判断当前用户是否登录(WEB)
def is_login_web(func):
    def wrapper(*args, **kwargs):
        if is_login():
            return func(*args, **kwargs)
        else:
            # 重定向登录页面 url_for(方法名称, 显示完整路径, url参数<?page_name=login.html>)
            return redirect(url_for("login_page", _external=True, page_name="login.html"))
    return wrapper


# 判断当前用户是否登录(API) ( 注意：@flask_app.route(endpoint='xxxx') 加上不同的路由映射视图函数名称，否则会报错)
def is_login_api(func):
    def wrapper(*args, **kwargs):
        if is_login():
            return func(*args, **kwargs)
        else:
            return json.dumps({"msg": "请先登录"}, ensure_ascii=False)
    return wrapper


"""
    页 面 接 口
"""


def base_varaible_dict():
    """
    获取 base.html 模板中的变量
    :return:
    """
    base_dict = dict()
    base_dict["api_addr"] = cfg.API_ADDR
    base_dict["pro_name_list"] = pro_name_list
    base_dict["pro_num"] = len(pro_name_list)
    return base_dict


# http://127.0.0.1:7060/login
@flask_app.route("/login", methods=["GET"])
def login_page():
    """   登 录 页 面   """
    page_name = request.args.get("page_name", "login.html")
    return render_template(page_name)


# http://127.0.0.1:7060/signin
@flask_app.route("/signin", methods=["GET"])
def singin_page():
    """   注 册 页 面   """
    return render_template('signin.html')


# http://127.0.0.1:7060/index
@flask_app.route("/index", methods=["GET"], endpoint="show_index")
@is_login_web
def show_index():
    """   首 页   """
    return render_template('index.html', tasks=base_varaible_dict())


# http://127.0.0.1:7060/case_page/pro_demo_1
@flask_app.route("/case_page/<pro_name>", methods=["GET"])
def case_page(pro_name):
    """   用 例 页 面   """
    if is_login():
        result_dict = base_varaible_dict()
        result_dict["pro_name"] = pro_name
        result_dict["is_run"] = pro_is_running(pro_name)
        result_dict["test_case_list"], result_dict["tag_name_list"] = show_case_by_test(pro_name=pro_name)
        result_dict["relation_list"] = get_relation_list(pro_name=pro_name, list_type="all")
        result_dict["statist_data"] = get_statist_data_for_case(pro_name)
        result_dict["host_list"], result_dict["global_variable_list"], \
            result_dict["cron_status"], result_dict["deploy_status"] = get_config_info(pro_name)
        result_dict["current_report_url"] = cfg.BASE_REPORT_EXCEL_PATH + pro_name + "/[API_report]" + pro_name + ".xls"
        result_dict["history_report_path"] = cfg.BASE_REPORT_EXCEL_PATH + pro_name + "/history/"
        return render_template('project.html', tasks=result_dict)
    else:
        # 重定向登录页面 url_for(方法名称, 显示完整路径, url参数<?page_name=login.html>)
        return redirect(url_for("login_page", _external=True, page_name="login.html"))


# http://127.0.0.1:7060/report_page/pro_demo_1
@flask_app.route("/report_page/<pro_name>", methods=["GET"])
def report_page(pro_name):
    """   测 试 报 告   """
    result_dict = base_varaible_dict()
    result_dict["pro_name"] = pro_name
    result_dict["is_run"] = pro_is_running(pro_name)
    result_dict["test_time_list"] = get_test_time_list(pro_name)
    last_test_time = result_dict["test_time_list"] and result_dict["test_time_list"][0] or ""
    result_dict["test_case_list"], result_dict["tag_name_list"] = \
        show_case_by_report(pro_name=pro_name, last_test_time=last_test_time)
    result_dict["current_relation_list"] = get_relation_list(pro_name=pro_name, list_type="test",
                                                             case_list=result_dict["test_case_list"])
    result_dict["statist_data"], result_dict["interface_name_list"], result_dict["http_rt_list"], \
        result_dict["bubble_list"] = get_statist_data_for_result(pro_name, last_test_time)
    result_dict["host"], result_dict["global_variable_dict"] = get_config_info_for_result(pro_name, last_test_time)
    return render_template('report.html', tasks=result_dict)


"""
    API 服 务 接 口
"""


@flask_app.route("/API/userIsAvailable", methods=["GET"])
def query_user_isAvailable():
    """
    查询用户是否存在 ( GET 请求 参数 )
    """
    username = request.args.get("username", "")
    res_info = {"valid": user_is_available(username=username)}
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/signin", methods=["POST"])
def api_signin():
    """
    注册接口 ( 正文格式：表单提交 )  < 非 前后端分离 >
    """
    form_params = request.form.to_dict()
    username = form_params.get("username", "").strip()
    password = form_params.get("password", "").strip()
    sign_in(username=username, password=password)
    # 重定向登录页面 url_for(方法名称, 显示完整路径, url参数<?page_name=login.html>)
    return redirect(url_for("login_page", _external=True, page_name="login.html"))


@flask_app.route("/API/login", methods=["POST"])
def api_login():
    """
    登录接口 ( 正文格式：表单提交 )  < 前后端分离 >
        1.登录页面通过AJAX调用该请求
        2.根据响应信息的 code 判断：是否跳转 index 页面
    """
    form_params = request.form.to_dict()
    username = form_params.get("username", "").strip()
    password = form_params.get("password", "").strip()
    remind = form_params.get("remind", "").strip()
    response = log_in(username=username, password=password, remind=remind)
    return response


@flask_app.route("/API/logout", methods=["GET"])
def api_logout():
    """
    退出登录接口  < 非 前后端分离 >
        1.第一次调用 /API/logout 接口 返回 302 状态码，并给出 /login 重定向地址
        2.第二次调用 /login 接口 跳转到登录页面 返回 200 状态码
    """
    token = request.cookies.get("token")
    if token is not None:
        dm = db_model(table=cfg.USER_INFO, error_msg="退出登录接口")
        dm.update_db(query={"token": token}, set_dict={"status": 0})
    # 重定向登录页面 url_for(方法名称, 显示完整路径, url参数<?page_name=login.html>)
    return redirect(url_for("login_page", _external=True, page_name="login.html"))


# http://localhost:1122/API/exec/deploy/local/pro_demo_1
# http://192.168.31.198:1180/API/exec/deploy/docker/pro_demo_1
@flask_app.route("/API/exec/<run_type>/<host_tag>/<pro_name>", methods=["GET"])
def exec_test(pro_name, run_type, host_tag):
    """
    执行测试（ 部署、定时、手动 ）
    :param pro_name：
    :param run_type：运行方式 manual | cron | deploy
    :param host_tag：HOST标记 local | docker
    :return:
    """
    res_info = dict()
    res_info["msg"] = run_test_by_pro(host=host_tag, pro_name=pro_name, run_type=run_type)
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/run_test/<pro_name>", methods=["POST"], endpoint='run_test')
@is_login_api
def run_test(pro_name):
    """
    执行测试 ( 页面执行 ) ( 正文格式：JSON )
    :param pro_name
    :return:
    """
    res_info = dict()
    host = request.json.get("host", "").strip()
    res_info["msg"] = run_test_by_pro(host=host, pro_name=pro_name, run_type="manual")
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/screen_test_time/<pro_name>", methods=["GET"])
def screen_test_time(pro_name):
    """
    通过'运行方式' 筛选 '测试时间'列表
    :param pro_name
           run_type: all | cron | manual | deploy
    :return:
    """
    res_info = dict()
    params = request.args
    run_type = params.get("run_type", "")  # str
    res_info["test_time_list"] = screen_test_time_by_run_type(pro_name, run_type)
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/screen_tag_name/<pro_name>", methods=["GET"])
def screen_tag_name(pro_name):
    """
    通过'测试时间' 筛选 '标签名称'列表
    :param pro_name
           test_time：2021-08-26 2016:26:41
    :return:
    """
    res_info = dict()
    params = request.args
    test_time = params.get("test_time", "")  # str
    res_info["tag_name_list"] = screen_tag_name_by_test_time(pro_name, test_time)
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/query_statist_data/<pro_name>", methods=["GET"])
def query_statist_data(pro_name):
    """
    获取统计数据
    :param pro_name
    :return:
    """
    res_info = dict()
    params = request.args
    test_time = params.get("test_time", "")  # str
    res_info["statist_data"], res_info["interface_name_list"], res_info["http_rt_list"], res_info["bubble_list"] = \
        get_statist_data_for_result(pro_name, test_time)
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/import_action/<pro_name>/<import_method>", methods=["POST"], endpoint='import_action')
@is_login_api
def import_action(pro_name, import_method):
    """
    导入用例操作
    :param pro_name
    :param import_method: 导入方式（批量新增、全部替换、批量替换）
    :return:
    """
    # 获取request中的upload文件
    upload_file = request.files.get("file", None)
    res_info = case_import_action(pro_name, upload_file, import_method)
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/generate_excel/<pro_name>", methods=["GET"])
def generate_excel(pro_name):
    """
    生成Excel报告
    :param pro_name
    :return:
    """
    res_info = dict()
    res_info["msg"] = generate_excel_with_statis_case(pro_name)
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/generate_swagger/<pro_name>", methods=["GET"])
def generate_swagger(pro_name):
    """
    生成Swagger解析
    :param pro_name
    :return:
    """
    res_info = dict()
    host = request.args.get("host", "")
    res_info["msg"] = swagger_prase(pro_name=pro_name, swagger_url=host+cfg.SWAGGER_BASE_URL).run()
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/get_run_status/<pro_name>", methods=["GET"])
def get_run_status(pro_name):
    """
    获取运行状态
    :param pro_name
    :return:
    """
    res_info = dict()
    res_info["is_run"] = pro_is_running(pro_name)
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/set_case_status_by_tag/<pro_name>", methods=["POST"])
def set_case_status_by_tag(pro_name):
    """
    通过标签 设置用例状态（上下线）
    :param pro_name:
    :return:
    """
    res_info = dict()
    tag_name = request.json.get("tag_name", "").strip()
    case_status = request.json.get("case_status", "").strip()
    res_info["msg"] = update_case_status_by_tag(pro_name, case_status, tag_name)
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/set_case_status/<pro_name>/<_id>", methods=["GET"])
def set_case_status(pro_name, _id):
    """
    设置某个'测试用例'的'状态'(上下线)
    :param pro_name:
    :param _id:
    :return:
    """
    new_case_status = None
    if is_null(pro_name) or is_null(_id):
        msg = PARAMS_NOT_NONE
    elif pro_is_running(pro_name):
        msg = CURRENT_IS_RUNNING
    else:
        new_case_status = update_case_status(pro_name, _id)
        msg = new_case_status == "mongo error" and MONGO_CONNECT_FAIL or UPDATE_SUCCESS
    re_dict = interface_template(msg, {"pro_name": pro_name, "_id": _id, "new_case_status": new_case_status})
    return json.dumps(re_dict, ensure_ascii=False)


@flask_app.route("/API/set_run_type_status/<pro_name>/<run_type>", methods=["GET"])
def set_run_type_status(pro_name, run_type):
    """
    修改 运行方式 任务状态
    :param pro_name:
    :param run_type: cron | deploy
    :return:
    """
    new_run_type_status = None
    if is_null(pro_name):
        msg = PARAMS_NOT_NONE
    else:
        new_run_type_status = update_run_type_status(pro_name, run_type)
        msg = new_run_type_status == "mongo error" and MONGO_CONNECT_FAIL or UPDATE_SUCCESS
    re_dict = interface_template(msg, {"pro_name": pro_name, "new_run_type_status": new_run_type_status})
    return json.dumps(re_dict, ensure_ascii=False)


@flask_app.route("/API/stop_run_status/<pro_name>", methods=["GET"])
def stop_run_status(pro_name):
    """
    停止用例运行状态
    :param pro_name
    :return:
    """
    res_info = dict()
    set_pro_run_status(pro_name=pro_name, run_status=False)
    res_info["msg"] = "停止成功"
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/search_case/<pro_name>/<table_tag>", methods=["GET"])
def search_case(pro_name, table_tag):
    """
    搜到用例
    :param pro_name
    :param table_tag:  _case | _result
    :return:
    """
    res_info = dict()
    res_info["is_run"] = pro_is_running(pro_name)
    res_info["test_case_list"], res_info["case_num"] = \
        get_case_search_result(request_args=request.args, pro_name=pro_name, table_tag=table_tag)
    if table_tag == "_result":
        res_info["current_relation_list"] = \
            get_relation_list(pro_name=pro_name, list_type="test", case_list=res_info["test_case_list"])
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/config_variable/<pro_name>/<config_type>", methods=["POST"])
def config_variable(pro_name, config_type):
    """
    配置变量（ HOST | 全局变量 ） （ 添加 | 编辑 ）
    :param pro_name
    :param config_type：host | global_variable
    :return:
    """
    res_info = dict()
    res_info["msg"] = get_config_result(request_json=request.json, pro_name=pro_name, config_type=config_type)
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/check_depend_variable/<pro_name>", methods=["GET"])
def check_depend_variable(pro_name):
    """
    检测依赖变量 是否配置正确
    :param pro_name:
    :return:
    """
    res_info = dict()
    res_info["msg"] = get_check_depend_variable_result(pro_name=pro_name)
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/check_global_variable/<pro_name>", methods=["GET"])
def check_global_variable(pro_name):
    """
    检测全局变量 是否配置正确
    :param pro_name:
    :return:
    """
    res_info = dict()
    res_info["msg"], global_variable_dict = get_check_global_variable_result(pro_name=pro_name)
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/operation_case/<mode>/<pro_name>", methods=["POST"])
def operation_case(pro_name, mode):
    """
    添加 | 编辑 用例
    :param pro_name
    :param mode  添加 add | 编辑 edit
    :return:
    """
    res_info = dict()
    res_info["msg"] = get_case_operation_result(request_json=request.json, pro_name=pro_name, mode=mode)
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/del_config/<pro_name>", methods=["DELETE"])
def del_config(pro_name):
    """
    删除配置 （ HOST | 全局变量 ）
    :param pro_name
    :return:
    """
    res_info = dict()
    res_info["msg"] = get_config_del_result(request_json=request.json, pro_name=pro_name)
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/del_case/<pro_name>", methods=["DELETE"])
def del_case(pro_name):
    """
    删除用例
    :param pro_name
    :return:
    """
    res_info = dict()
    res_info["msg"] = get_case_del_result(request_json=request.json, pro_name=pro_name)
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/get_current_case/<pro_name>", methods=["POST"])
def get_current_case(pro_name):
    """
    获取已有用例（填充新增弹层）
    :return:
    """
    res_info = dict()
    res_info["test_case"] = get_case_by_name(request_json=request.json, pro_name=pro_name)
    return json.dumps(res_info, ensure_ascii=False)


@flask_app.route("/API/get_case_by_id/<pro_name>/<table_tag>", methods=["GET"])
def get_case(pro_name, table_tag):
    """
    通过id获取用例（填充编辑弹层、模态框显示接口信息）
    :param pro_name
    :param table_tag:  _case | _result
    :return:
    """
    res_info = dict()
    res_info["test_case"] = get_case_by_id(request_args=request.args, pro_name=pro_name, table_tag=table_tag)
    return json.dumps(res_info, ensure_ascii=False)


"""
#################################【 以 下 为 测 试 接 口（ 供 debug 使 用 ） 】###########################################
"""

"""
    【 上 下 游 接 口 】 场景一：[ 新增用户, 删除用户 ]
    新增用户：下游关联字段 = uid
    删除用户：上游关联用例 = 查询用户 （ URL：uid,name ）
"""


# http://127.0.0.1:7060/test/add_user
@flask_app.route("/test/add_user", methods=["POST"])
def test_add_user():
    """ 新增用户 """
    params = request.json
    token = params.get("token", "")
    uid = "UID" + str(random.randint(100000, 999999))
    result_dict = {"uid": uid, "name": u"用户名称", "token": token}
    re_dict = interface_template(INSERT_SUCCESS, result_dict)
    response = Response(json.dumps(re_dict))
    response.headers["Content-Type"] = "application/json; charest=utf-8"
    return response


# http://127.0.0.1:7060/test/del_user/<uid>
@flask_app.route("/test/del_user/<uid>", methods=["POST", "DELETE"])
def test_del_user(uid):
    """ 删除用户 """
    params = request.json
    name = params.get("name", "")
    token = params.get("token", "")
    result_dict = {"uid": uid, "name": name, "token": token}
    re_dict = interface_template(DELETE_SUCCESS, result_dict)
    response = Response(json.dumps(re_dict))
    response.headers["Content-Type"] = "application/json; charest=utf-8"
    return response


"""
    【 上 下 游 接 口 】 场景二：[ 接口1, 接口2, 接口3 ]
    接口1：下游关联字段 = key1
    接口2：上游关联用例 = 接口1，下游关联字段 = key2 （ 正文体：key1 ）
    接口3：上游关联用例 = 接口2（ 正文体：key1， 请求参数：key2 ）
"""


# http://127.0.0.1:7060/test/test_scene_two_1
@flask_app.route("/test/test_scene_two_1", methods=["POST"])
def test_scene_two_1():
    """ 场景二：接口1 """
    params = request.json
    token = params.get("token", "")
    result_dict = {"token": token, "key1": "test_scene_two_1"}
    re_dict = interface_template(REQUEST_SUCCESS, result_dict)
    response = Response(json.dumps(re_dict))
    response.headers["Content-Type"] = "application/json; charest=utf-8"
    return response


# http://127.0.0.1:7060/test/test_scene_two_2
@flask_app.route("/test/test_scene_two_2", methods=["POST"])
def test_scene_two_2():
    """ 场景二：接口2 """
    params = request.json
    token = params.get("token", "")
    key1 = params.get("key1", "")
    result_dict = {"token": token, "key1": key1, "key2": "test_scene_two_2"}
    re_dict = interface_template(REQUEST_SUCCESS, result_dict)
    response = Response(json.dumps(re_dict))
    response.headers["Content-Type"] = "application/json; charest=utf-8"
    return response


# http://127.0.0.1:7060/test/test_scene_two_3?key2=[key2]
@flask_app.route("/test/test_scene_two_3", methods=["POST"])
def test_scene_two_3():
    """ 场景二：接口3 """
    token = request.json.get("token", "")
    key1 = request.json.get("key1", "")
    key2 = request.args.get("key2", "")
    result_dict = {"token": token, "key1": key1, "key2": key2, "done": "关联接口调用成功！"}
    re_dict = interface_template(REQUEST_SUCCESS, result_dict)
    response = Response(json.dumps(re_dict))
    response.headers["Content-Type"] = "application/json; charest=utf-8"
    return response


"""
    【 上 下 游 接 口 】 场景三：[ 接口1, 接口2, 接口3 ]
    接口1：下游关联字段 = test1
    接口2：上游关联用例 = 接口1，下游关联字段 = test2
    接口3：上游关联用例 = 接口2（ 正文体：test1，头文件：test2 ）
"""


# http://127.0.0.1:7060/test/test_scene_three_1
@flask_app.route("/test/test_scene_three_1", methods=["POST"])
def test_scene_three_1():
    """ 场景三：接口1 """
    params = request.json
    token = params.get("token", "")
    result_dict = {"token": token, "test1": "test_scene_three_1"}
    re_dict = interface_template(REQUEST_SUCCESS, result_dict)
    response = Response(json.dumps(re_dict))
    response.headers["Content-Type"] = "application/json; charest=utf-8"
    return response


# http://127.0.0.1:7060/test/test_scene_three_2
@flask_app.route("/test/test_scene_three_2", methods=["POST"])
def test_scene_three_2():
    """ 场景三：接口2 """
    params = request.json
    token = params.get("token", "")
    result_dict = {"token": token, "test2": "application/json"}
    re_dict = interface_template(REQUEST_SUCCESS, result_dict)
    response = Response(json.dumps(re_dict))
    response.headers["Content-Type"] = "application/json; charest=utf-8"
    return response


# http://127.0.0.1:7060/test/test_scene_three_3
@flask_app.route("/test/test_scene_three_3", methods=["POST"])
def test_scene_three_3():
    """ 场景三：接口3 """
    token = request.json.get("token", "")
    test1 = request.json.get("test1", "")
    result_dict = {"token": token, "test1": test1, "done": "关联接口调用成功！"}
    re_dict = interface_template(REQUEST_SUCCESS, result_dict)
    response = Response(json.dumps(re_dict))
    response.headers["Content-Type"] = "application/json; charest=utf-8"
    return response


"""
    【 上 下 游 接 口 】 场景四：[ 发表评论, 查询评论, 删除评论 ]
    发表评论：下游关联字段 = comment
    查询评论：上游关联用例 = 发表评论，下游关联字段 = c_id（ 通过comment获取 ）
    删除评论：上游关联用例 = 查询评论（ 正文体：c_id ）
    
    《 备 注 》
    场景问题: 由于'发表评论'接口没有返回新增的'评论ID',导致'删除评论'时无法获取最新添加的'评论ID'
    解决方案: 通过'查询评论'接口,获取到所有评论信息列表,再通过'最新发表的内容'找到'评论ID'
"""


# http://127.0.0.1:7060/test/add_comment
@flask_app.route("/test/add_comment", methods=["POST"])
def test_add_comment():
    """ 发表评论 """
    params = request.json
    token = params.get("token", "")
    comment = params.get("comment", "")
    result_dict = {"comment": comment, "token": token}
    re_dict = interface_template(INSERT_SUCCESS, result_dict)
    response = Response(json.dumps(re_dict))
    response.headers["Content-Type"] = "application/json; charest=utf-8"
    return response


# http://127.0.0.1:7060/test/search_comment
@flask_app.route("/test/search_comment", methods=["POST"])
def test_search_comment():
    """ 查询评论 """
    params = request.json
    token = params.get("token", "")
    result_dict = {"token": token, "comment_list": [{"c_id": "CID11111", "comment": "第一条评论"},
                                                    {"c_id": "CID22222", "comment": "第二条评论"},
                                                    {"c_id": "CID33333", "comment": "新增的评论"}]}
    re_dict = interface_template(SEARCH_SUCCESS, result_dict)
    response = Response(json.dumps(re_dict))
    response.headers["Content-Type"] = "application/json; charest=utf-8"
    return response


# # http://127.0.0.1:7060/test/search_comment
# @flask_app.route("/test/search_comment/<num>", methods=["POST"])
# def test_search_comment(num):
#     """ 查询评论 """
#     params = request.json
#     token = params.get("token", "")
#     if num == "1":
#         result_dict = {"token": token, "c_id": "CID11111", "comment": "第一条评论"}
#     else:
#         result_dict = {"token": token, "c_id": "CID22222", "comment": "第二条评论"}
#     re_dict = interface_template(SEARCH_SUCCESS, result_dict)
#     response = Response(json.dumps(re_dict))
#     response.headers["Content-Type"] = "application/json; charest=utf-8"
#     return response


# conditon = comment_list[?@.comment==[comment]].c_id
#  c_id::<conditon>
# http://127.0.0.1:7060/test/del_comment
@flask_app.route("/test/del_comment", methods=["POST", "DELETE"])
def test_del_comment():
    """ 删除评论 """
    params = request.json
    token = params.get("token", "")
    c_id = params.get("c_id", "")
    result_dict = {"评论ID": c_id, "token": token}
    re_dict = interface_template(DELETE_SUCCESS, result_dict)
    response = Response(json.dumps(re_dict))
    response.headers["Content-Type"] = "application/json; charest=utf-8"
    return response



"""
  【 不 需 要 依 赖 的 接 口 】
"""


# http://127.0.0.1:7060/test/test_get_request_no_params
@flask_app.route("/test/test_get_request_no_params", methods=["GET"])
def test_get_request_no_params():
    result_dict = {"pro_name": "pro_demo_1", "browser_name": "Chrome"}
    msg = CASE_RUNING
    re_dict = interface_template(msg, result_dict)
    return json.dumps(re_dict, ensure_ascii=False)


# http://127.0.0.1:7060/test/test_get_request?test_str=接口自动化测试&test_int=5&test_bool=True
@flask_app.route("/test/test_get_request", methods=["GET"])
def test_get_request():
    params = request.args
    test_str = params.get("test_str", "")  # str
    test_int = params.get("test_int", "")  # str
    test_bool = params.get("test_bool", "")  # str
    result_dict = {"test_str": test_str, "test_int": test_int, "test_bool": test_bool}
    msg = REQUEST_SUCCESS
    re_dict = interface_template(msg, result_dict)
    return json.dumps(re_dict, ensure_ascii=False)


# http://127.0.0.1:7060/test/test_post_request
@flask_app.route("/test/test_post_request", methods=["POST"])
def test_post_request():
    params = request.json
    test_str = params.get("test_str")  # str
    test_int = params.get("test_int")   # int
    test_bool = params.get("test_bool")  # str
    response_list = ["list_str", 5, True]
    response_dict = {"name": "Messi", "age": 32, "sex": True}
    response_list_dict = [{"name": "Henry", "age": 43}, {"name": "Ronaldo", "age": 40},
                          {"name": "Backham", "age": 44}, {"name": "Moreno", "age": 34}]
    result_dict = {"test_str": test_str, "test_int": test_int, "test_bool": test_bool, "response_list": response_list,
                   "response_dict": response_dict, "response_list_dict": response_list_dict}
    msg = SYNC_SUCCESS
    re_dict = interface_template(msg, result_dict)
    return json.dumps(re_dict, ensure_ascii=False)


"""
    【 依 赖 接 口 逻 辑 】
    1.获取图片：  依赖接口 < 登录 >         依赖字段 < token >
    2.依赖get：  依赖接口 < 登录,获取图片 >  依赖字段 < token,image_id >
    3.依赖post： 依赖接口 < 登录,获取图片 >  依赖字段 < token,image_id >
"""


# http://127.0.0.1:7060/test/login
@flask_app.route("/test/login", methods=["POST"])
def test_login():
    """
    登录接口 - < 入参格式：json >
        默认账号：micllo / 123456

       验 证 逻 辑
       1.获取请求中的用户名、密码
       2.获取数据库中的用户名、密码、uid
       3.比较用户名、密码
       4.生成 token = MD5 ( 用户名 + 三个随机数 + MD5密码 )
       5.生成 key = MD5 ( uid + 三个随机数 + token )

       返回 依赖 字段
       1.响应体 返回：token
       2.响应头 返回：key
    """
    msg = ""
    result_dict = {}
    if request.content_type != "application/json":
        msg = CONTENT_TYPE_WRONG
    else:
        # 获取请求中的用户名、密码
        params = request.json
        name = params.get("name")  # str
        passwd = params.get("passwd")   # int
        # 获取数据库中的用户名、密码、uid
        name_db = "micllo"
        passwd_db = md5("123456")
        uid = "U1234567890abcdefg"
        # 比较用户名、密码
        if name_db == name:
            if passwd_db == md5(str(passwd)):
                # 随机生成三位数字符串
                random_num = str(random.randint(100, 999))
                # 生成 token = MD5 ( 用户名 + 三个随机数 + MD5密码 )
                token = md5(name + random_num + passwd_db)
                # 生成 key = MD5 ( uid + 三个随机数 + token )
                key = md5(str(uid) + random_num + token)
                tmp1 = {"test": "111", "demo": "aaa", "key": "第二个key值"}
                tmp2 = {"test": "222", "demo": "bbb"}
                result_dict = {"name_db": name_db, "passwd_db": passwd_db, "token": token, "key": key,
                               "tmp1": tmp1, "tmp2": tmp2}
                msg = REQUEST_SUCCESS
            else:
                msg = PASSWORD_ERROR
        else:
            msg = USERNAME_ERROR
    re_dict = interface_template(msg, result_dict)
    response = Response(json.dumps(re_dict))
    response.headers["Content-Type"] = "application/json; charest=utf-8"
    return response


# http://127.0.0.1:7060/test/get_image?token=123456
@flask_app.route("/test/get_image", methods=["GET"])
def test_get_image():
    """
    获取图片接口
     需要的依赖参数
      1.token
     返回的依赖参数
      1.image_id
    :return:
    """
    params = request.args
    token = params.get("token", "")
    result_dict = {"image_id": "I_1234567890", "token": token}
    msg = REQUEST_SUCCESS
    re_dict = interface_template(msg, result_dict)
    return json.dumps(re_dict, ensure_ascii=False)


# http://127.0.0.1:7060/test/depend_get?image_id=xxxx&token=xxxx
@flask_app.route("/test/depend_get", methods=["GET"])
def test_depend_get():
    """
    依赖get接口
     需要的依赖参数
      1.token
      2.image_id
    :return:
    """
    params = request.args
    image_id = params.get("image_id", "")
    token = params.get("token", "")
    result_dict = {"image_id": image_id, "token": token, "info": "messi_get"}
    msg = REQUEST_SUCCESS
    re_dict = interface_template(msg, result_dict)
    return json.dumps(re_dict, ensure_ascii=False)


# http://127.0.0.1:7060/test/depend_get2/xxxxxxxx?token=xxxx
@flask_app.route("/test/depend_get2/<image_id>", methods=["GET"])
def test_depend_get2(image_id):
    """
    依赖get接口2
     需要的依赖参数
      1.image_id
    :return:
    """
    params = request.args
    token = params.get("token", "")
    result_dict = {"image_id": image_id, "token": token, "info": "messi_get2"}
    msg = REQUEST_SUCCESS
    re_dict = interface_template(msg, result_dict)
    return json.dumps(re_dict, ensure_ascii=False)


# http://127.0.0.1:7060/test/depend_post
@flask_app.route("/test/depend_post", methods=["POST"])
def test_depend_post():
    """
    依赖post接口
     需要的依赖参数
      1.token
      2.image_id
      3.Content_Type
    :return:
    """
    params = request.json
    image_id = params.get("image_id", "")
    token = params.get("token", "")
    result_dict = {"image_id": image_id, "token": token, "info": "messi_post"}
    msg = REQUEST_SUCCESS
    re_dict = interface_template(msg, result_dict)
    return json.dumps(re_dict, ensure_ascii=False)


@flask_app.route("/test/form_post", methods=["POST", "PUT", "DELETE"])
def test_form_post():
    """
    form_post接口- < 入参格式：form >
    :return:
    """
    if request.content_type != "application/x-www-form-urlencoded":
        result_dict = {"content_type": request.content_type}
        msg = CONTENT_TYPE_WRONG
    else:
        params = request.form
        form_name = params.get("form_name", "")
        result_dict = {"form_name": form_name}
        msg = REQUEST_SUCCESS
    re_dict = interface_template(msg, result_dict)
    return json.dumps(re_dict, ensure_ascii=False)


@flask_app.route("/test/json_post", methods=["POST", "PUT", "DELETE"])
def test_json_post():
    """
    json_post接口- < 入参格式：json >
    :return:
    """
    if request.content_type != "application/json":
        result_dict = {"content_type": request.content_type}
        msg = CONTENT_TYPE_WRONG
    else:
        params = request.json
        json_name = params.get("json_name", "")
        result_dict = {"json_name": json_name}
        msg = REQUEST_SUCCESS
    re_dict = interface_template(msg, result_dict)
    return json.dumps(re_dict, ensure_ascii=False)


# http://127.0.0.1:7060/test/test_celery_send_task/55/66
@flask_app.route("/test/test_celery_send_task/<x>/<y>", methods=["GET"])
def test_celery_send_task(x, y):
    """
        执行 celery 发布任务
        逻辑：
            1.调用接口后，通过 delay() 方法 将task任务存入消息队列中，返回创建的任务结果
                （1）result.id -> 任务 ID
                （2）result.id -> 任务状态：PENDING, START, SUCCESS
            2.celery work 监听服务 获取任务并执行
                celery -A Celery_program.celery_app worker --loglevel=info
    """
    result = celery_task.celery_demo_task.delay(x, y)
    result_dict = {"msg": f"任务已提交，请稍后查询, 任务ID：{result.id}"}
    return json.dumps(result_dict, ensure_ascii=False)


# http://127.0.0.1:7060/test/test_celery_query_result/<task_id>
@flask_app.route("/test/test_celery_query_result/<task_id>", methods=["GET"])
def test_celery_query_result(task_id):
    """
        通过 task_id 从 redis 中查询 celery 执行结果
    """
    redis = redisResult()
    result_dict = redis.get_res(task_id)
    return json.dumps(result_dict, ensure_ascii=False)